package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("UnitRestController")
public class UnitRestController extends CmiEmaController {

	/**
	 * Create a new Unit entity
	 * 
	 */
	@RequestMapping(value = "/newUnit", method = RequestMethod.POST)
	@ResponseBody
	public Object newUnit(@RequestBody Unit unit) {
		unitService.saveUnit(unit);
		return JSONObject.parse(cmiPsonService.toJsonString(unitDAO.findUnitByPrimaryKey(unit.getId()), 2));
	}

	@RequestMapping(value = "/restNewUnit", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewUnit(@RequestBody String unitJson) {
		Unit unit = new Gson().fromJson(unitJson, Unit.class);
		appendReferences(unit);
		unitService.saveUnit(unit);
		return JSONObject.parse(cmiPsonService.toJsonString(unitDAO.findUnitByPrimaryKey(unit.getId()), 2));
	}

	@RequestMapping(value = "/saveUnit", method = RequestMethod.PUT)
	@ResponseBody
	public Unit saveUnit(@RequestBody Unit unit) {
		unitService.saveUnit(unit);
		return unitDAO.findUnitByPrimaryKey(unit.getId());
	}

	@RequestMapping(value = "/restSaveUnit", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveUnit(@RequestBody String unitJson) {
		Unit unit = new Gson().fromJson(unitJson, Unit.class);
		appendReferences(unit);
		CmiPsonService cmiPsonService = new CmiPsonService();
		unitService.saveUnit(unit);
		return JSONObject.parse(cmiPsonService.toJsonString(unitDAO.findUnitByPrimaryKey(unit.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteUnit/{unitId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteUnit(@PathVariable Integer unitId) {
		Unit unit = unitDAO.findUnitByPrimaryKey(unitId);
		unitService.deleteUnit(unit);
	}

	@RequestMapping(value = "/restConfirmDeleteUnits")
	@ResponseBody
	public Object restConfirmDeleteUnits(@RequestBody Set<Integer> deleteUnitsIds) {
		Set<Unit> deleteUnits = unitDAO.findUnitsByIds(deleteUnitsIds);
		Set<Unit> referencedUnits = unitService.loadReferenceUnits(deleteUnits);
		deleteUnits.removeAll(referencedUnits);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedUnits);
		jsonObject.put("deleteEntitys", deleteUnits);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteUnits")
	@ResponseBody
	public Object restDeleteUnits(@RequestBody Set<Unit> deleteUnits) {
		Iterator<Unit> iterator = deleteUnits.iterator();
		while (iterator.hasNext()) {
			Unit currentUnit = iterator.next();
			unitService.deleteUnit(currentUnit);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listUnits");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadUnit/{unitId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnit(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadUnitAdditiveaddresss/{unitId}/additiveaddresss/{relatedadditiveaddressId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitAdditiveaddresss(@PathVariable Integer unitId,
			@PathVariable Integer relatedadditiveaddressId, @RequestBody CmiPagination cmiPagination) {
		Additiveaddress additiveaddress = additiveaddressDAO.findAdditiveaddressByPrimaryKey(relatedadditiveaddressId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(additiveaddress, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitDetectdetails/{unitId}/detectdetails/{relateddetectdetailId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitDetectdetails(@PathVariable Integer unitId, @PathVariable Integer relateddetectdetailId,
			@RequestBody CmiPagination cmiPagination) {
		Detectdetail detectdetail = detectdetailDAO.findDetectdetailByPrimaryKey(relateddetectdetailId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectdetail, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitDetectfeatures/{unitId}/detectfeatures/{relateddetectfeatureId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitDetectfeatures(@PathVariable Integer unitId, @PathVariable Integer relateddetectfeatureId,
			@RequestBody CmiPagination cmiPagination) {
		Detectfeature detectfeature = detectfeatureDAO.findDetectfeatureByPrimaryKey(relateddetectfeatureId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectfeature, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitDetectstandards/{unitId}/detectstandards/{relateddetectstandardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitDetectstandards(@PathVariable Integer unitId,
			@PathVariable Integer relateddetectstandardId, @RequestBody CmiPagination cmiPagination) {
		Detectstandard detectstandard = detectstandardDAO.findDetectstandardByPrimaryKey(relateddetectstandardId, -1,
				-1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(detectstandard, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitExpires/{unitId}/expires/{relatedexpireId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitExpires(@PathVariable Integer unitId, @PathVariable Integer relatedexpireId,
			@RequestBody CmiPagination cmiPagination) {
		Expire expire = expireDAO.findExpireByPrimaryKey(relatedexpireId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(expire, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitFeaturestandards/{unitId}/featurestandards/{relatedfeaturestandardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitFeaturestandards(@PathVariable Integer unitId,
			@PathVariable Integer relatedfeaturestandardId, @RequestBody CmiPagination cmiPagination) {
		Featurestandard featurestandard = featurestandardDAO.findFeaturestandardByPrimaryKey(relatedfeaturestandardId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(featurestandard, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitFoodbatchs/{unitId}/foodbatchs/{relatedfoodbatchId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitFoodbatchs(@PathVariable Integer unitId, @PathVariable Integer relatedfoodbatchId,
			@RequestBody CmiPagination cmiPagination) {
		Foodbatch foodbatch = foodbatchDAO.findFoodbatchByPrimaryKey(relatedfoodbatchId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodbatch, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitFoodbatchfillers/{unitId}/foodbatchfillers/{relatedfoodbatchfillerId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitFoodbatchfillers(@PathVariable Integer unitId,
			@PathVariable Integer relatedfoodbatchfillerId, @RequestBody CmiPagination cmiPagination) {
		Foodbatchfiller foodbatchfiller = foodbatchfillerDAO.findFoodbatchfillerByPrimaryKey(relatedfoodbatchfillerId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodbatchfiller, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitFoodsaleaddresss/{unitId}/foodsaleaddresss/{relatedfoodsaleaddressId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitFoodsaleaddresss(@PathVariable Integer unitId,
			@PathVariable Integer relatedfoodsaleaddressId, @RequestBody CmiPagination cmiPagination) {
		Foodsaleaddress foodsaleaddress = foodsaleaddressDAO.findFoodsaleaddressByPrimaryKey(relatedfoodsaleaddressId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodsaleaddress, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitMaterialaddresss/{unitId}/materialaddresss/{relatedmaterialaddressId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitMaterialaddresss(@PathVariable Integer unitId,
			@PathVariable Integer relatedmaterialaddressId, @RequestBody CmiPagination cmiPagination) {
		Materialaddress materialaddress = materialaddressDAO.findMaterialaddressByPrimaryKey(relatedmaterialaddressId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(materialaddress, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitPackingmethods/{unitId}/packingmethods/{relatedpackingmethodId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitPackingmethods(@PathVariable Integer unitId, @PathVariable Integer relatedpackingmethodId,
			@RequestBody CmiPagination cmiPagination) {
		Packingmethod packingmethod = packingmethodDAO.findPackingmethodByPrimaryKey(relatedpackingmethodId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(packingmethod, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitProcessmethods/{unitId}/processmethods/{relatedprocessmethodId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitProcessmethods(@PathVariable Integer unitId, @PathVariable Integer relatedprocessmethodId,
			@RequestBody CmiPagination cmiPagination) {
		Processmethod processmethod = processmethodDAO.findProcessmethodByPrimaryKey(relatedprocessmethodId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(processmethod, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitPurchaseadditives/{unitId}/purchaseadditives/{relatedpurchaseadditiveId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitPurchaseadditives(@PathVariable Integer unitId,
			@PathVariable Integer relatedpurchaseadditiveId, @RequestBody CmiPagination cmiPagination) {
		Purchaseadditive purchaseadditive = purchaseadditiveDAO
				.findPurchaseadditiveByPrimaryKey(relatedpurchaseadditiveId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(purchaseadditive, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadUnitPurchasematerials/{unitId}/purchasematerials/{relatedpurchasematerialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadUnitPurchasematerials(@PathVariable Integer unitId,
			@PathVariable Integer relatedpurchasematerialId, @RequestBody CmiPagination cmiPagination) {
		Purchasematerial purchasematerial = purchasematerialDAO
				.findPurchasematerialByPrimaryKey(relatedpurchasematerialId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(purchasematerial, 2, cmiPagination));
	}

	public void appendReferences(Unit unit) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Additiveaddress> additiveaddresssForUnit = new HashSet<>();
		for (Additiveaddress additiveaddress_Unit : unit.getAdditiveaddresssForUnit()) {
			additiveaddresssForUnit
					.add(additiveaddressService.findAdditiveaddressByPrimaryKey(additiveaddress_Unit.getId()));
		}
		unit.setAdditiveaddresssForUnit(additiveaddresssForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detectdetail> detectdetailsForUnit = new HashSet<>();
		for (Detectdetail detectdetail_Unit : unit.getDetectdetailsForUnit()) {
			detectdetailsForUnit.add(detectdetailService.findDetectdetailByPrimaryKey(detectdetail_Unit.getId()));
		}
		unit.setDetectdetailsForUnit(detectdetailsForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detectfeature> detectfeaturesForUnit = new HashSet<>();
		for (Detectfeature detectfeature_Unit : unit.getDetectfeaturesForUnit()) {
			detectfeaturesForUnit.add(detectfeatureService.findDetectfeatureByPrimaryKey(detectfeature_Unit.getId()));
		}
		unit.setDetectfeaturesForUnit(detectfeaturesForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Detectstandard> detectstandardsForUnit = new HashSet<>();
		for (Detectstandard detectstandard_Unit : unit.getDetectstandardsForUnit()) {
			detectstandardsForUnit
					.add(detectstandardService.findDetectstandardByPrimaryKey(detectstandard_Unit.getId()));
		}
		unit.setDetectstandardsForUnit(detectstandardsForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Expire> expiresForUnit = new HashSet<>();
		for (Expire expire_Unit : unit.getExpiresForUnit()) {
			expiresForUnit.add(expireService.findExpireByPrimaryKey(expire_Unit.getId()));
		}
		unit.setExpiresForUnit(expiresForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Featurestandard> featurestandardsForUnit = new HashSet<>();
		for (Featurestandard featurestandard_Unit : unit.getFeaturestandardsForUnit()) {
			featurestandardsForUnit
					.add(featurestandardService.findFeaturestandardByPrimaryKey(featurestandard_Unit.getId()));
		}
		unit.setFeaturestandardsForUnit(featurestandardsForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodbatch> foodbatchsForUnit = new HashSet<>();
		for (Foodbatch foodbatch_Unit : unit.getFoodbatchsForUnit()) {
			foodbatchsForUnit.add(foodbatchService.findFoodbatchByPrimaryKey(foodbatch_Unit.getId()));
		}
		unit.setFoodbatchsForUnit(foodbatchsForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodbatchfiller> foodbatchfillersForUnit = new HashSet<>();
		for (Foodbatchfiller foodbatchfiller_Unit : unit.getFoodbatchfillersForUnit()) {
			foodbatchfillersForUnit
					.add(foodbatchfillerService.findFoodbatchfillerByPrimaryKey(foodbatchfiller_Unit.getId()));
		}
		unit.setFoodbatchfillersForUnit(foodbatchfillersForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodsaleaddress> foodsaleaddresssForUnit = new HashSet<>();
		for (Foodsaleaddress foodsaleaddress_Unit : unit.getFoodsaleaddresssForUnit()) {
			foodsaleaddresssForUnit
					.add(foodsaleaddressService.findFoodsaleaddressByPrimaryKey(foodsaleaddress_Unit.getId()));
		}
		unit.setFoodsaleaddresssForUnit(foodsaleaddresssForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Materialaddress> materialaddresssForUnit = new HashSet<>();
		for (Materialaddress materialaddress_Unit : unit.getMaterialaddresssForUnit()) {
			materialaddresssForUnit
					.add(materialaddressService.findMaterialaddressByPrimaryKey(materialaddress_Unit.getId()));
		}
		unit.setMaterialaddresssForUnit(materialaddresssForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Packingmethod> packingmethodsForUnit = new HashSet<>();
		for (Packingmethod packingmethod_Unit : unit.getPackingmethodsForUnit()) {
			packingmethodsForUnit.add(packingmethodService.findPackingmethodByPrimaryKey(packingmethod_Unit.getId()));
		}
		unit.setPackingmethodsForUnit(packingmethodsForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Processmethod> processmethodsForUnit = new HashSet<>();
		for (Processmethod processmethod_Unit : unit.getProcessmethodsForUnit()) {
			processmethodsForUnit.add(processmethodService.findProcessmethodByPrimaryKey(processmethod_Unit.getId()));
		}
		unit.setProcessmethodsForUnit(processmethodsForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Purchaseadditive> purchaseadditivesForUnit = new HashSet<>();
		for (Purchaseadditive purchaseadditive_Unit : unit.getPurchaseadditivesForUnit()) {
			purchaseadditivesForUnit
					.add(purchaseadditiveService.findPurchaseadditiveByPrimaryKey(purchaseadditive_Unit.getId()));
		}
		unit.setPurchaseadditivesForUnit(purchaseadditivesForUnit);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Purchasematerial> purchasematerialsForUnit = new HashSet<>();
		for (Purchasematerial purchasematerial_Unit : unit.getPurchasematerialsForUnit()) {
			purchasematerialsForUnit
					.add(purchasematerialService.findPurchasematerialByPrimaryKey(purchasematerial_Unit.getId()));
		}
		unit.setPurchasematerialsForUnit(purchasematerialsForUnit);
	}

	@RequestMapping(value = "/restGetUnitAdditiveaddresss/{unitId}/additiveaddresss", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitAdditiveaddresss(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getAdditiveaddresssForUnit(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitDetectdetails/{unitId}/detectdetails", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitDetectdetails(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getDetectdetailsForUnit(), 2,
				cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitDetectfeatures/{unitId}/detectfeatures", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitDetectfeatures(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getDetectfeaturesForUnit(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitDetectstandards/{unitId}/detectstandards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitDetectstandards(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getDetectstandardsForUnit(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitExpires/{unitId}/expires", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitExpires(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getExpiresForUnit(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitFeaturestandards/{unitId}/featurestandards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitFeaturestandards(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getFeaturestandardsForUnit(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitFoodbatchs/{unitId}/foodbatchs", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitFoodbatchs(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getFoodbatchsForUnit(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitFoodbatchfillers/{unitId}/foodbatchfillers", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitFoodbatchfillers(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getFoodbatchfillersForUnit(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitFoodsaleaddresss/{unitId}/foodsaleaddresss", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitFoodsaleaddresss(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getFoodsaleaddresssForUnit(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitMaterialaddresss/{unitId}/materialaddresss", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitMaterialaddresss(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getMaterialaddresssForUnit(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitPackingmethods/{unitId}/packingmethods", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitPackingmethods(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getPackingmethodsForUnit(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitProcessmethods/{unitId}/processmethods", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitProcessmethods(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getProcessmethodsForUnit(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitPurchaseadditives/{unitId}/purchaseadditives", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitPurchaseadditives(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getPurchaseadditivesForUnit(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetUnitPurchasematerials/{unitId}/purchasematerials", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetUnitPurchasematerials(@PathVariable Integer unitId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(unitDAO.findUnitByPrimaryKey(unitId).getPurchasematerialsForUnit(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListUnits", method = RequestMethod.GET)
	@ResponseBody
	public Object restListUnits() {
		return JSONObject.parse(cmiPsonService.toJsonString(unitService.loadUnits(), 2));
	}

	@RequestMapping(value = "/restListUnitsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListUnitsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = unitPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Unit> units = unitDAO.findAllUnits(startResult, cmiPagination.getPaginationSize());
		String unitString = cmiPsonService.toPsonString(units, 2, cmiPagination);

		return JSONObject.parse(unitString);
	}

	@RequestMapping("/unitSelectBox")
	@ResponseBody
	public JSONObject unitSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Additiveaddress":
				entitySet = additiveaddressService.loadAdditiveaddresssByIdSet(searchValue);
				break;
			case "Detectdetail":
				entitySet = detectdetailService.loadDetectdetailsByIdSet(searchValue);
				break;
			case "Detectfeature":
				entitySet = detectfeatureService.loadDetectfeaturesByIdSet(searchValue);
				break;
			case "Detectstandard":
				entitySet = detectstandardService.loadDetectstandardsByIdSet(searchValue);
				break;
			case "Expire":
				entitySet = expireService.loadExpiresByIdSet(searchValue);
				break;
			case "Featurestandard":
				entitySet = featurestandardService.loadFeaturestandardsByIdSet(searchValue);
				break;
			case "Foodbatch":
				entitySet = foodbatchService.loadFoodbatchsByIdSet(searchValue);
				break;
			case "Foodbatchfiller":
				entitySet = foodbatchfillerService.loadFoodbatchfillersByIdSet(searchValue);
				break;
			case "Foodsaleaddress":
				entitySet = foodsaleaddressService.loadFoodsaleaddresssByIdSet(searchValue);
				break;
			case "Materialaddress":
				entitySet = materialaddressService.loadMaterialaddresssByIdSet(searchValue);
				break;
			case "Packingmethod":
				entitySet = packingmethodService.loadPackingmethodsByIdSet(searchValue);
				break;
			case "Processmethod":
				entitySet = processmethodService.loadProcessmethodsByIdSet(searchValue);
				break;
			case "Purchaseadditive":
				entitySet = purchaseadditiveService.loadPurchaseadditivesByIdSet(searchValue);
				break;
			case "Purchasematerial":
				entitySet = purchasematerialService.loadPurchasematerialsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Additiveaddress":
				entitySet = additiveaddressDAO.findAllAdditiveaddresss((pageNumber - 1) * paginationSize,
						paginationSize);
				count = additiveaddressService.countAdditiveaddresss();
				break;
			case "Detectdetail":
				entitySet = detectdetailDAO.findAllDetectdetails((pageNumber - 1) * paginationSize, paginationSize);
				count = detectdetailService.countDetectdetails();
				break;
			case "Detectfeature":
				entitySet = detectfeatureDAO.findAllDetectfeatures((pageNumber - 1) * paginationSize, paginationSize);
				count = detectfeatureService.countDetectfeatures();
				break;
			case "Detectstandard":
				entitySet = detectstandardDAO.findAllDetectstandards((pageNumber - 1) * paginationSize, paginationSize);
				count = detectstandardService.countDetectstandards();
				break;
			case "Expire":
				entitySet = expireDAO.findAllExpires((pageNumber - 1) * paginationSize, paginationSize);
				count = expireService.countExpires();
				break;
			case "Featurestandard":
				entitySet = featurestandardDAO.findAllFeaturestandards((pageNumber - 1) * paginationSize,
						paginationSize);
				count = featurestandardService.countFeaturestandards();
				break;
			case "Foodbatch":
				entitySet = foodbatchDAO.findAllFoodbatchs((pageNumber - 1) * paginationSize, paginationSize);
				count = foodbatchService.countFoodbatchs();
				break;
			case "Foodbatchfiller":
				entitySet = foodbatchfillerDAO.findAllFoodbatchfillers((pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodbatchfillerService.countFoodbatchfillers();
				break;
			case "Foodsaleaddress":
				entitySet = foodsaleaddressDAO.findAllFoodsaleaddresss((pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodsaleaddressService.countFoodsaleaddresss();
				break;
			case "Materialaddress":
				entitySet = materialaddressDAO.findAllMaterialaddresss((pageNumber - 1) * paginationSize,
						paginationSize);
				count = materialaddressService.countMaterialaddresss();
				break;
			case "Packingmethod":
				entitySet = packingmethodDAO.findAllPackingmethods((pageNumber - 1) * paginationSize, paginationSize);
				count = packingmethodService.countPackingmethods();
				break;
			case "Processmethod":
				entitySet = processmethodDAO.findAllProcessmethods((pageNumber - 1) * paginationSize, paginationSize);
				count = processmethodService.countProcessmethods();
				break;
			case "Purchaseadditive":
				entitySet = purchaseadditiveDAO.findAllPurchaseadditives((pageNumber - 1) * paginationSize,
						paginationSize);
				count = purchaseadditiveService.countPurchaseadditives();
				break;
			case "Purchasematerial":
				entitySet = purchasematerialDAO.findAllPurchasematerials((pageNumber - 1) * paginationSize,
						paginationSize);
				count = purchasematerialService.countPurchasematerials();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Additiveaddress":
				entitySet = additiveaddressDAO.findAdditiveaddressByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = additiveaddressService.countAdditiveaddresssByName(queryword);
				break;
			case "Detectdetail":
				entitySet = detectdetailDAO.findDetectdetailByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectdetailService.countDetectdetailsByName(queryword);
				break;
			case "Detectfeature":
				entitySet = detectfeatureDAO.findDetectfeatureByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectfeatureService.countDetectfeaturesByName(queryword);
				break;
			case "Detectstandard":
				entitySet = detectstandardDAO.findDetectstandardByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectstandardService.countDetectstandardsByName(queryword);
				break;
			case "Expire":
				entitySet = expireDAO.findExpireByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = expireService.countExpiresByName(queryword);
				break;
			case "Featurestandard":
				entitySet = featurestandardDAO.findFeaturestandardByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = featurestandardService.countFeaturestandardsByName(queryword);
				break;
			case "Foodbatch":
				entitySet = foodbatchDAO.findFoodbatchByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodbatchService.countFoodbatchsByName(queryword);
				break;
			case "Foodbatchfiller":
				entitySet = foodbatchfillerDAO.findFoodbatchfillerByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = foodbatchfillerService.countFoodbatchfillersByName(queryword);
				break;
			case "Foodsaleaddress":
				entitySet = foodsaleaddressDAO.findFoodsaleaddressByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = foodsaleaddressService.countFoodsaleaddresssByName(queryword);
				break;
			case "Materialaddress":
				entitySet = materialaddressDAO.findMaterialaddressByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = materialaddressService.countMaterialaddresssByName(queryword);
				break;
			case "Packingmethod":
				entitySet = packingmethodDAO.findPackingmethodByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = packingmethodService.countPackingmethodsByName(queryword);
				break;
			case "Processmethod":
				entitySet = processmethodDAO.findProcessmethodByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = processmethodService.countProcessmethodsByName(queryword);
				break;
			case "Purchaseadditive":
				entitySet = purchaseadditiveDAO.findPurchaseadditiveByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = purchaseadditiveService.countPurchaseadditivesByName(queryword);
				break;
			case "Purchasematerial":
				entitySet = purchasematerialDAO.findPurchasematerialByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = purchasematerialService.countPurchasematerialsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
